import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime, timedelta
import numpy as np
import sys
import os

# 添加src和styles到路径
sys.path.append(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'src'))
sys.path.append(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'styles'))

from models.order_fulfillment import OrderFulfillmentAnalyzer
from models.inventory_model import InventoryAnalyzer
from common_styles import apply_common_styles, create_page_title, create_metric_card

# 应用统一样式
apply_common_styles()

# 初始化订单分析器
@st.cache_resource
def init_order_analyzer():
    return OrderFulfillmentAnalyzer()

order_analyzer = init_order_analyzer()

# 页面标题
create_page_title("订单管理系统", "📋")

# 侧边栏功能选择
st.sidebar.title("功能菜单")
function = st.sidebar.selectbox(
    "选择功能",
    ["📊 订单概览", "➕ 新建订单", "📝 订单管理", "📈 订单分析", "🚚 物流跟踪", "📋 订单报表"]
)

# 订单概览
if function == "📊 订单概览":
    st.header("订单概览")
    
    # 关键指标
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        st.markdown(create_metric_card("127", "今日订单", "+23"), unsafe_allow_html=True)
    
    with col2:
        st.markdown(create_metric_card("45", "待处理订单", "-8"), unsafe_allow_html=True)
    
    with col3:
        st.markdown(create_metric_card("94.2%", "订单完成率", "+2.1%"), unsafe_allow_html=True)
    
    with col4:
        st.markdown(create_metric_card("2.3天", "平均处理时间", "-0.5天"), unsafe_allow_html=True)
    
    st.markdown("---")
    
    # 订单状态分布
    col1, col2 = st.columns(2)
    
    with col1:
        st.subheader("订单状态分布")
        status_data = pd.DataFrame({
            '状态': ['待处理', '处理中', '已完成', '已取消'],
            '数量': [45, 82, 234, 12],
            '占比': [12.1, 22.0, 62.7, 3.2]
        })
        fig_status = px.pie(status_data, values='数量', names='状态',
                           title="订单状态分布",
                           color_discrete_map={
                               '待处理': '#ff9800',
                               '处理中': '#2196f3', 
                               '已完成': '#4caf50',
                               '已取消': '#f44336'
                           })
        st.plotly_chart(fig_status, use_container_width=True)
    
    with col2:
        st.subheader("订单优先级分布")
        priority_data = pd.DataFrame({
            '优先级': ['紧急', '高', '中', '低'],
            '数量': [23, 67, 189, 94]
        })
        fig_priority = px.bar(priority_data, x='优先级', y='数量',
                             title="订单优先级分布",
                             color='优先级',
                             color_discrete_map={
                                 '紧急': '#f44336',
                                 '高': '#ff9800',
                                 '中': '#2196f3',
                                 '低': '#4caf50'
                             })
        st.plotly_chart(fig_priority, use_container_width=True)
    
    # 近期订单趋势
    st.subheader("近30天订单趋势")
    dates = pd.date_range(start=datetime.now() - timedelta(days=30), end=datetime.now(), freq='D')
    trend_data = pd.DataFrame({
        '日期': dates,
        '订单数量': [80 + i*2 + (i%7)*10 + np.random.randint(-15, 15) for i in range(len(dates))],
        '订单金额': [150000 + i*3000 + (i%7)*20000 + np.random.randint(-30000, 30000) for i in range(len(dates))]
    })
    
    col1, col2 = st.columns(2)
    with col1:
        fig_count = px.line(trend_data, x='日期', y='订单数量', title="每日订单数量趋势")
        st.plotly_chart(fig_count, use_container_width=True)
    
    with col2:
        fig_amount = px.line(trend_data, x='日期', y='订单金额', title="每日订单金额趋势")
        st.plotly_chart(fig_amount, use_container_width=True)
    
    # 待处理订单列表
    st.subheader("待处理订单（Top 10）")
    pending_orders = pd.DataFrame({
        '订单号': ['ORD2024001', 'ORD2024002', 'ORD2024003', 'ORD2024004', 'ORD2024005',
                  'ORD2024006', 'ORD2024007', 'ORD2024008', 'ORD2024009', 'ORD2024010'],
        '客户': ['华为技术', '小米科技', '比亚迪', '宁德时代', '美的集团',
               '格力电器', '海尔智家', '京东方', '立讯精密', '三一重工'],
        '订单金额': [156000, 89000, 234000, 178000, 123000,
                    98000, 167000, 145000, 189000, 134000],
        '下单时间': ['2024-01-15 09:30', '2024-01-15 14:20', '2024-01-16 11:15', 
                   '2024-01-16 16:45', '2024-01-17 08:30', '2024-01-17 13:20',
                   '2024-01-18 10:15', '2024-01-18 15:30', '2024-01-19 09:45', '2024-01-19 14:10'],
        '优先级': ['高', '中', '紧急', '高', '中', '低', '高', '中', '紧急', '中'],
        '预计交付': ['2024-01-20', '2024-01-22', '2024-01-18', '2024-01-21', '2024-01-24',
                   '2024-01-26', '2024-01-23', '2024-01-25', '2024-01-20', '2024-01-27']
    })
    
    st.dataframe(pending_orders, use_container_width=True)

# 新建订单
elif function == "➕ 新建订单":
    st.header("新建订单")
    
    with st.form("create_order_form"):
        # 基本信息
        st.subheader("基本信息")
        col1, col2 = st.columns(2)
        
        with col1:
            customer_name = st.selectbox("客户名称*", 
                                       ["华为技术", "小米科技", "比亚迪", "宁德时代", "美的集团"])
            order_type = st.selectbox("订单类型*", ["销售订单", "采购订单", "内部调拨", "退货订单"])
            priority = st.selectbox("优先级*", ["紧急", "高", "中", "低"])
        
        with col2:
            delivery_date = st.date_input("要求交付日期*", datetime.now() + timedelta(days=7))
            payment_terms = st.selectbox("付款条件", ["现金", "30天", "60天", "90天"])
            sales_person = st.selectbox("销售人员", ["张经理", "李主管", "王总监", "陈专员"])
        
        # 收货信息
        st.subheader("收货信息")
        col3, col4 = st.columns(2)
        
        with col3:
            delivery_address = st.text_area("收货地址*")
            contact_person = st.text_input("联系人*")
        
        with col4:
            contact_phone = st.text_input("联系电话*")
            special_requirements = st.text_area("特殊要求")
        
        # 订单明细
        st.subheader("订单明细")
        
        # 动态添加订单项
        if 'order_items' not in st.session_state:
            st.session_state.order_items = [{'product': '', 'quantity': 0, 'price': 0}]
        
        for i, item in enumerate(st.session_state.order_items):
            col1, col2, col3, col4, col5 = st.columns([3, 2, 2, 2, 1])
            
            with col1:
                product = st.selectbox(f"产品{i+1}", 
                                     ["产品A", "产品B", "产品C", "产品D", "产品E"],
                                     key=f"product_{i}")
            with col2:
                quantity = st.number_input(f"数量{i+1}", min_value=0, key=f"quantity_{i}")
            with col3:
                price = st.number_input(f"单价{i+1}", min_value=0.0, key=f"price_{i}")
            with col4:
                amount = quantity * price
                st.text_input(f"金额{i+1}", value=f"{amount:.2f}", disabled=True, key=f"amount_{i}")
            with col5:
                if st.button("删除", key=f"delete_{i}"):
                    st.session_state.order_items.pop(i)
                    st.experimental_rerun()
        
        col1, col2 = st.columns([1, 4])
        with col1:
            if st.button("添加产品"):
                st.session_state.order_items.append({'product': '', 'quantity': 0, 'price': 0})
                st.experimental_rerun()
        
        # 订单汇总
        st.subheader("订单汇总")
        total_amount = sum([item.get('quantity', 0) * item.get('price', 0) for item in st.session_state.order_items])
        tax_rate = st.number_input("税率(%)", min_value=0.0, max_value=100.0, value=13.0) / 100
        tax_amount = total_amount * tax_rate
        final_amount = total_amount + tax_amount
        
        col1, col2, col3 = st.columns(3)
        with col1:
            st.metric("商品总额", f"¥{total_amount:,.2f}")
        with col2:
            st.metric("税额", f"¥{tax_amount:,.2f}")
        with col3:
            st.metric("订单总额", f"¥{final_amount:,.2f}")
        
        # 提交按钮
        col1, col2 = st.columns(2)
        with col1:
            submitted = st.form_submit_button("创建订单", type="primary")
        with col2:
            draft_saved = st.form_submit_button("保存草稿")
        
        if submitted:
            if customer_name and delivery_date and delivery_address and contact_person and contact_phone:
                order_number = f"ORD{datetime.now().strftime('%Y%m%d%H%M%S')}"
                st.success(f"订单 '{order_number}' 创建成功！")
                st.balloons()
                # 清空订单项
                st.session_state.order_items = [{'product': '', 'quantity': 0, 'price': 0}]
            else:
                st.error("请填写所有必填字段（标*的字段）")
        
        if draft_saved:
            st.info("订单草稿已保存")

# 订单管理
elif function == "📝 订单管理":
    st.header("订单管理")
    
    # 搜索和筛选
    col1, col2, col3, col4 = st.columns(4)
    with col1:
        search_term = st.text_input("搜索订单", placeholder="输入订单号或客户名称")
    with col2:
        status_filter = st.selectbox("订单状态", ["全部", "待处理", "处理中", "已完成", "已取消"])
    with col3:
        priority_filter = st.selectbox("优先级", ["全部", "紧急", "高", "中", "低"])
    with col4:
        date_range = st.date_input("日期范围", [datetime.now() - timedelta(days=7), datetime.now()])
    
    # 订单列表
    orders_data = pd.DataFrame({
        '订单号': ['ORD2024001', 'ORD2024002', 'ORD2024003', 'ORD2024004', 'ORD2024005',
                  'ORD2024006', 'ORD2024007', 'ORD2024008', 'ORD2024009', 'ORD2024010'],
        '客户名称': ['华为技术', '小米科技', '比亚迪', '宁德时代', '美的集团',
                   '格力电器', '海尔智家', '京东方', '立讯精密', '三一重工'],
        '订单金额': [156000, 89000, 234000, 178000, 123000,
                    98000, 167000, 145000, 189000, 134000],
        '下单时间': ['2024-01-15', '2024-01-15', '2024-01-16', '2024-01-16', '2024-01-17',
                   '2024-01-17', '2024-01-18', '2024-01-18', '2024-01-19', '2024-01-19'],
        '状态': ['待处理', '处理中', '已完成', '处理中', '待处理',
               '已完成', '处理中', '已完成', '待处理', '处理中'],
        '优先级': ['高', '中', '紧急', '高', '中', '低', '高', '中', '紧急', '中'],
        '预计交付': ['2024-01-20', '2024-01-22', '2024-01-18', '2024-01-21', '2024-01-24',
                   '2024-01-26', '2024-01-23', '2024-01-25', '2024-01-20', '2024-01-27'],
        '销售人员': ['张经理', '李主管', '王总监', '陈专员', '张经理',
                   '李主管', '王总监', '陈专员', '张经理', '李主管']
    })
    
    # 应用筛选
    filtered_data = orders_data.copy()
    if search_term:
        filtered_data = filtered_data[
            filtered_data['订单号'].str.contains(search_term, case=False, na=False) |
            filtered_data['客户名称'].str.contains(search_term, case=False, na=False)
        ]
    if status_filter != "全部":
        filtered_data = filtered_data[filtered_data['状态'] == status_filter]
    if priority_filter != "全部":
        filtered_data = filtered_data[filtered_data['优先级'] == priority_filter]
    
    # 显示筛选后的数据
    st.subheader(f"订单列表 (共{len(filtered_data)}条)")
    
    # 添加操作列
    def make_clickable(order_id):
        return f'<a href="#" onclick="alert(\"查看订单 {order_id}\")">查看</a> | <a href="#" onclick="alert(\"编辑订单 {order_id}\")">编辑</a>'
    
    display_data = filtered_data.copy()
    display_data['操作'] = display_data['订单号'].apply(make_clickable)
    
    st.dataframe(display_data, use_container_width=True)
    
    # 批量操作
    st.subheader("批量操作")
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        if st.button("批量确认"):
            st.success("已批量确认选中订单")
    with col2:
        if st.button("批量取消"):
            st.warning("已批量取消选中订单")
    with col3:
        if st.button("导出Excel"):
            st.success("订单数据已导出")
    with col4:
        if st.button("打印订单"):
            st.info("正在准备打印...")

# 订单分析
elif function == "📈 订单分析":
    st.header("订单分析")
    
    # 时间范围选择
    col1, col2 = st.columns(2)
    with col1:
        start_date = st.date_input("开始日期", datetime.now() - timedelta(days=30))
    with col2:
        end_date = st.date_input("结束日期", datetime.now())
    
    # 关键指标
    st.subheader("关键指标")
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        st.metric("总订单数", "1,234", "156")
    with col2:
        st.metric("总订单金额", "¥12.5M", "¥2.1M")
    with col3:
        st.metric("平均订单金额", "¥10,125", "¥1,234")
    with col4:
        st.metric("客户数量", "89", "12")
    
    # 订单趋势分析
    st.subheader("订单趋势分析")
    
    # 生成模拟数据
    import numpy as np
    dates = pd.date_range(start=start_date, end=end_date, freq='D')
    trend_data = pd.DataFrame({
        '日期': dates,
        '订单数量': [80 + i*2 + (i%7)*10 + np.random.randint(-15, 15) for i in range(len(dates))],
        '订单金额': [150000 + i*3000 + (i%7)*20000 + np.random.randint(-30000, 30000) for i in range(len(dates))]
    })
    
    col1, col2 = st.columns(2)
    
    with col1:
        fig_trend = px.line(trend_data, x='日期', y='订单数量', title="订单数量趋势")
        st.plotly_chart(fig_trend, use_container_width=True)
    
    with col2:
        fig_amount = px.line(trend_data, x='日期', y='订单金额', title="订单金额趋势")
        st.plotly_chart(fig_amount, use_container_width=True)
    
    # 客户分析
    st.subheader("客户分析")
    
    col1, col2 = st.columns(2)
    
    with col1:
        # Top客户
        top_customers = pd.DataFrame({
            '客户': ['华为技术', '小米科技', '比亚迪', '宁德时代', '美的集团'],
            '订单数': [45, 38, 32, 28, 25],
            '订单金额': [2100000, 1800000, 1650000, 1400000, 1200000]
        })
        fig_customers = px.bar(top_customers, x='客户', y='订单金额', title="Top 5客户订单金额")
        st.plotly_chart(fig_customers, use_container_width=True)
    
    with col2:
        # 订单金额分布
        amount_ranges = pd.DataFrame({
            '金额范围': ['<1万', '1-5万', '5-10万', '10-50万', '>50万'],
            '订单数': [234, 456, 289, 178, 67]
        })
        fig_ranges = px.pie(amount_ranges, values='订单数', names='金额范围', title="订单金额分布")
        st.plotly_chart(fig_ranges, use_container_width=True)
    
    # 产品分析
    st.subheader("产品分析")
    
    product_analysis = pd.DataFrame({
        '产品': ['产品A', '产品B', '产品C', '产品D', '产品E'],
        '销售数量': [1200, 980, 756, 634, 523],
        '销售金额': [2400000, 1960000, 1512000, 1268000, 1046000],
        '平均单价': [2000, 2000, 2000, 2000, 2000]
    })
    
    col1, col2 = st.columns(2)
    
    with col1:
        fig_product_qty = px.bar(product_analysis, x='产品', y='销售数量', title="产品销售数量")
        st.plotly_chart(fig_product_qty, use_container_width=True)
    
    with col2:
        fig_product_amount = px.bar(product_analysis, x='产品', y='销售金额', title="产品销售金额")
        st.plotly_chart(fig_product_amount, use_container_width=True)

# 物流跟踪
elif function == "🚚 物流跟踪":
    st.header("物流跟踪")
    
    # 订单选择
    col1, col2 = st.columns(2)
    with col1:
        order_number = st.selectbox("选择订单", 
                                  ['ORD2024001', 'ORD2024002', 'ORD2024003', 'ORD2024004', 'ORD2024005'])
    with col2:
        tracking_number = st.text_input("或输入物流单号")
    
    # 物流信息
    st.subheader("物流信息")
    
    logistics_info = {
        'ORD2024001': {
            '物流公司': '顺丰速运',
            '物流单号': 'SF1234567890',
            '发货时间': '2024-01-16 14:30',
            '预计到达': '2024-01-18 16:00',
            '当前状态': '运输中',
            '当前位置': '上海分拨中心'
        }
    }
    
    if order_number in logistics_info:
        info = logistics_info[order_number]
        
        col1, col2, col3 = st.columns(3)
        with col1:
            st.info(f"**物流公司**: {info['物流公司']}")
            st.info(f"**物流单号**: {info['物流单号']}")
        with col2:
            st.info(f"**发货时间**: {info['发货时间']}")
            st.info(f"**预计到达**: {info['预计到达']}")
        with col3:
            st.info(f"**当前状态**: {info['当前状态']}")
            st.info(f"**当前位置**: {info['当前位置']}")
    
    # 物流轨迹
    st.subheader("物流轨迹")
    
    tracking_data = pd.DataFrame({
        '时间': ['2024-01-16 14:30', '2024-01-16 18:45', '2024-01-17 08:20', 
               '2024-01-17 15:30', '2024-01-18 09:15'],
        '地点': ['上海仓库', '上海分拨中心', '杭州转运中心', '宁波分拨中心', '宁波配送站'],
        '状态': ['已发货', '运输中', '运输中', '运输中', '派送中'],
        '备注': ['商品已从仓库发出', '到达分拨中心', '正在转运中', '到达目的地分拨中心', '正在派送']
    })
    
    # 使用时间线样式显示
    for i, row in tracking_data.iterrows():
        col1, col2 = st.columns([1, 4])
        with col1:
            st.write(f"**{row['时间']}**")
        with col2:
            if row['状态'] == '派送中':
                st.success(f"📍 {row['地点']} - {row['状态']} - {row['备注']}")
            elif row['状态'] == '运输中':
                st.info(f"🚚 {row['地点']} - {row['状态']} - {row['备注']}")
            else:
                st.write(f"📦 {row['地点']} - {row['状态']} - {row['备注']}")
    
    # 地图显示（模拟）
    st.subheader("配送路线")
    st.info("🗺️ 配送路线地图功能开发中...")
    
    # 配送统计
    st.subheader("配送统计")
    
    col1, col2, col3 = st.columns(3)
    with col1:
        st.metric("在途订单", "45")
    with col2:
        st.metric("今日配送", "23")
    with col3:
        st.metric("平均配送时间", "2.3天")

# 订单报表
elif function == "📋 订单报表":
    st.header("订单报表")
    
    # 报表类型选择
    report_type = st.selectbox("选择报表类型", 
                              ["订单汇总报表", "客户订单报表", "产品销售报表", "订单完成率报表", "订单趋势报表"])
    
    # 时间范围
    col1, col2 = st.columns(2)
    with col1:
        start_date = st.date_input("开始日期", datetime.now() - timedelta(days=30))
    with col2:
        end_date = st.date_input("结束日期", datetime.now())
    
    if report_type == "订单汇总报表":
        st.subheader("订单汇总报表")
        
        summary_data = pd.DataFrame({
            '指标': ['总订单数', '总订单金额', '平均订单金额', '已完成订单', '待处理订单', 
                   '已取消订单', '完成率', '取消率'],
            '数值': ['1,234', '¥12,500,000', '¥10,125', '1,156', '65', '13', '93.7%', '1.1%'],
            '环比': ['+12.5%', '+18.3%', '+5.2%', '+11.8%', '-8.5%', '+2.1%', '+1.2%', '-0.3%']
        })
        
        st.dataframe(summary_data, use_container_width=True)
        
        # 图表展示
        col1, col2 = st.columns(2)
        
        with col1:
            status_chart_data = pd.DataFrame({
                '状态': ['已完成', '待处理', '已取消'],
                '数量': [1156, 65, 13]
            })
            fig_status = px.pie(status_chart_data, values='数量', names='状态', title="订单状态分布")
            st.plotly_chart(fig_status, use_container_width=True)
        
        with col2:
            # 月度趋势
            monthly_data = pd.DataFrame({
                '月份': ['2023-10', '2023-11', '2023-12', '2024-01'],
                '订单数': [980, 1050, 1180, 1234],
                '订单金额': [9800000, 10500000, 11800000, 12500000]
            })
            fig_monthly = px.line(monthly_data, x='月份', y='订单数', title="月度订单趋势")
            st.plotly_chart(fig_monthly, use_container_width=True)
    
    elif report_type == "客户订单报表":
        st.subheader("客户订单报表")
        
        customer_data = pd.DataFrame({
            '客户名称': ['华为技术', '小米科技', '比亚迪', '宁德时代', '美的集团', '格力电器', '海尔智家', '京东方'],
            '订单数量': [45, 38, 32, 28, 25, 22, 19, 16],
            '订单金额': [2100000, 1800000, 1650000, 1400000, 1200000, 1100000, 950000, 800000],
            '平均订单金额': [46667, 47368, 51563, 50000, 48000, 50000, 50000, 50000],
            '完成率': ['95.6%', '92.1%', '96.9%', '89.3%', '92.0%', '95.5%', '94.7%', '93.8%']
        })
        
        st.dataframe(customer_data, use_container_width=True)
        
        # 客户排名图表
        fig_customer = px.bar(customer_data.head(5), x='客户名称', y='订单金额', title="Top 5客户订单金额")
        st.plotly_chart(fig_customer, use_container_width=True)
    
    # 导出功能
    st.subheader("报表导出")
    col1, col2, col3 = st.columns(3)
    
    with col1:
        if st.button("导出Excel"):
            st.success("报表已导出为Excel文件")
    
    with col2:
        if st.button("导出PDF"):
            st.success("报表已导出为PDF文件")
    
    with col3:
        if st.button("发送邮件"):
            st.success("报表已发送到指定邮箱")

# 页脚
st.markdown("---")
st.markdown("**订单管理系统** | 高效订单处理与跟踪")